#ifndef __LINEAR_SENSE_BARRIER_BARRIER_H__
#define __LINEAR_SENSE_BARRIER_BARRIER_H__

#include "IBarrier.h"
#include "cpp_framework.h"
#include "Globals.h"
#include <assert.h>

using namespace CMDR;

class LSBThreadLocal : public ThreadLocal<int>
{
public:
	int initialValue() { return 0; }
};

class LSBSenseThreadLocal : public ThreadLocal<int>
{
public:
	int initialValue() { return 0; }
};

class LinearSenseBarrier : public IBarrier {
private:
	CMDR::AtomicInteger _count;
	unsigned int _size;
	int volatile _sense;
	
	AtomicBoolean* _threadDoneArray;
	
	LSBSenseThreadLocal *threadSense;
	LSBThreadLocal *threadId;
public:
	
	/* C'tor */
	LinearSenseBarrier(int n) : _size(n)
	{
		_count.set(n);
		_sense = 1;

		threadId = new LSBThreadLocal();
		threadSense = new LSBSenseThreadLocal();
		_threadDoneArray = new AtomicBoolean[n];

		for (int i = 0; i < n; i++)
		{
			_threadDoneArray[i].set(false);
		}
	}

	inline virtual char* getBarrierName()
	{
		return "LinearSenseBarrier";
	}

	/*
	 * inits that _threadID and _threadSense thread specifics.
	 */
	virtual void initThreadLocals(int);

	/* D'tor */
	virtual ~LinearSenseBarrier() {}
	
	/*
	 * Impl of the pure virtual function.  
	 */	
	void await();
};


#endif /*__LINEAR_SENSE_BARRIER_BARRIER_H__*/
